<template>
  <view
    :style="{
      height: PhoneInfo.windowHeight + 'px',
      width: PhoneInfo.windowWidth + 'px',
    }"
  >
    <mvBar :mysNavConfig="mysNavConfig" @onLeftClick="onLeftClick"></mvBar>
    <!-- 消息提示 -->
    <u-toast ref="uToast"></u-toast>
    <view style="margin: 2% 4%">
      <u-search
        v-model="searchKeyword"
        @search="this.getEquipmentList()"
        shape="round"
        bgColor="#fff"
        borderColor="#c4c6c9"
        placeholderColor="#c4c6c9"
        :clearabled="true"
        :showAction="true"
        actionText="新增"
        @custom="gotoAdd"
        input-align="left"
      >
      </u-search>
    </view>
    <u-tabs
      :list="list"
      lineWidth="90"
      :scrollable="false"
      lineColor="#3c9cff"
      :activeStyle="{
        color: '#303133',
        fontWeight: 'bold',
        fontSize: '14px',
        transform: 'scale(1.05)',
      }"
      :inactiveStyle="{
        color: '#606266',
        fontSize: '14px',
        transform: 'scale(1)',
      }"
      itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"
      @click="clicktab"
    >
    </u-tabs>
    <view style="height: 1290rpx" v-show="!noData">
      <scroll-view
        scroll-y="true"
        style="height: 100%"
        @scrolltolower="scrolltolower"
      >
        <view
          v-for="(item, index) in equipmentList"
          :key="item.equipmentRealId"
          class="swipecolleq"
        >
          <u-swipe-action>
            <u-swipe-action-item
              :disabled="item.isnohua"
              :options="options"
              @click="EQdelclick(item)"
            >
              <uni-collapse @change="collapse(item)">
                <uni-collapse-item titleBorder="none">
                  <template v-slot:title>
                    <uni-list :border="false">
                      <uni-list-item @longpress="longpress(item)">
                        <template v-slot:header>
                          <view class="slot-box slotheader">
                            <u-album
                              :urls="item.picUrl"
                              maxCount="1"
                              :showMore="false"
                            ></u-album>
                          </view>
                        </template>
                        <template v-slot:body>
                          <view class="slotbo" @click="goEditEQ(item)">
                            <view class="slottitle"
                              >{{ item.name
                              }}<text
                                class="uni-description"
                                v-if="item.assignFlag == 1"
                                >(授权人:{{ item.assigner }})</text
                              >
                            </view>
                            <view class="slottext">{{ item.description }}</view>
                          </view>
                        </template>
                      </uni-list-item>
                    </uni-list>
                  </template>
                  <uni-list
                    v-for="(value, number) in item.points"
                    :key="number"
                    :border="true"
                  >
                    <u-swipe-action>
                      <u-swipe-action-item
                        :disabled="item.assignFlag == 1 ? true : false"
                        :options="options"
                        @click="delPOclick(item, value)"
                      >
                        <uni-list-item>
                          <template v-slot:header>
                            <view class="slot-box slotheader">
                              <u-album
                                :urls="value.picUrl"
                                maxCount="1"
                                :showMore="false"
                              ></u-album>
                            </view>
                          </template>
                          <template v-slot:body>
                            <view
                              class="slotbody"
                              @click="goEditPO(item, value)"
                            >
                              <view class="slottitle">{{ value.name }}</view>
                              <view class="slottext">{{
                                value.description
                              }}</view>
                            </view>
                          </template>
                          <template v-slot:footer>
                            <view class="slotfooter">
                              <view
                                @click="gosensor(item, value)"
                                style="background-color: #3f86e9"
                              >
                                {{
                                  value.deviceMac !== "" &&
                                  value.deviceMac !== null
                                    ? "传"
                                    : "绑"
                                }}
                              </view>
                              <view
                                @click="setabnormal(item, value)"
                                style="background-color: #fe9349"
                                >警</view
                              >
                            </view>
                          </template>
                        </uni-list-item>
                      </u-swipe-action-item>
                    </u-swipe-action>
                  </uni-list>
                  <!-- 新增测点 -->
                  <uni-list :border="true">
                    <uni-list-item>
                      <template v-slot:body>
                        <view class="xinzeng" @click="addpoint(item)">
                          <uni-icons
                            type="plus-filled"
                            size="35"
                            color="#2979ff"
                          ></uni-icons>
                          <view class="slottitle" style="color: #2979ff"
                            >新增测点</view
                          >
                        </view>
                      </template>
                    </uni-list-item>
                  </uni-list>
                </uni-collapse-item>
              </uni-collapse>
            </u-swipe-action-item>
          </u-swipe-action>
        </view>
      </scroll-view>
    </view>
    <view v-show="noData">
      <view class="header">
        <image
          mode="aspectFit"
          src="/static/img/nodata.png"
          style="width: 320px; height: 240px"
        ></image>
      </view>
      <view class="title">
        <text>{{ nodatatitle }}</text>
      </view>
    </view>
    <!-- 复制弹窗 -->
    <view>
      <u-modal
        :show="show"
        confirmColor="#2979ff"
        confirmText="复制"
        title="复制后的设备名称为"
        :showCancelButton="true"
        @confirm="confirm"
        @cancel="this.show = false"
      >
        <view style="width: 80%">
          <u--input
            placeholder="请输入设备名称"
            border="bottom"
            v-model="copyvalue"
          ></u--input>
        </view>
      </u-modal>
    </view>
    <u-loadmore
      :status="loadStatus"
      :loading-text="loadingText"
      :loadmore-text="loadmoreText"
      nomore-text=" "
      bgColor="#f2f5f9"
    ></u-loadmore>
  </view>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      PhoneInfo: "",
      nodatatitle: "您还没有创建设备，请先创建需要监测的设备。",
      mysNavConfig: {
        /* 占位开启  */
        navPadding: true,
        /* 背景 */
        bgColor: "#2979FF",
        /* 标题 （屏幕中心居中 两边图标中心居中使用slot center1） */
        navTitle: {
          text: "设备列表",
          color: "#ffffff",
          fontSize: "18px", // px upx rpx
          fontWeight: "500", // 100 - 700
        },
        isCustomFn: true,
        btnType: "type2",
        type2Config: {
          // 左图标
          leftPath: "/static/img/back.png",
          // 右图标
          rightPath: "/static/img/home.png",
          // 圆角
          radius: "40rpx",
        },
      },
      //删除图标
      options: [
        {
          icon: "trash-fill",
          iconSize: "20",
          style: {
            backgroundColor: "#f56c6c",
            width: "40px",
            height: "40px",
            borderRadius: "100px",
            margin: "0 6px",
          },
        },
      ],
      list: [
        {
          id: 1,
          name: "我创建的设备",
        },
        {
          id: 2,
          name: "授权给我的设备",
        },
      ],
      createlist: [], //创建列表
      entrustlist: [], //授权列表
      current: 1,
      searchKeyword: "",
      userinfo: "",
      equipmentList: [],
      pageIndex: 1,
      pageSize: 8,
      count: 0,
      showCreated: 1, //我创建的设备
      showAssigned: 1, //授权给我的设备
      loadStatus: "loadmore",
      loadingText: "加载中...",
      loadmoreText: "上拉加载更多",
      copyequipmentid: "",
      copyvalue: "",
      show: false,
      noData: false,
    };
  },
  onLoad(parameter) {
    this.PhoneInfo = this.$utils.GetPhoneInfo();
    this.userinfo = uni.getStorageSync("userinfo");
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });
    uni.request({
      url:
        getApp().globalData.serverAddress +
        this.$uri.Uri_lookEquipmentList.replace(
          "{userRealId}",
          this.userinfo.userRealId
        ),
      data: {
        page: this.pageIndex,
        limit: this.pageSize,
        showCreated: this.showCreated,
        showAssigned: this.showAssigned,
      },
      dataType: "json",
      method: "GET",
      success: (res) => {
        if (res.statusCode !== 200) {
          this.$utils.showToast(
            this,
            "服务器错误,请联系技术支持人员!",
            "error"
          );
          return;
        }
        if (res.data.code == 0) {
          for (let items of res.data.data) {
            //照片处理
            if (items.picUrl.length !== 0 && items.picUrl[0] !== "") {
              var arr = [];
              for (let val of items.picUrl) {
                arr.push(getApp().globalData.serverAddress + val);
              }
              items.picUrl = arr;
            } else {
              items.picUrl[0] = "/static/img/NoPictures.png";
            }
            //assignFlag是0  表示是创建  1的时候表示授权
            if (items.assignFlag == 0) {
              //创建滑动不被禁用
              items.isnohua = false;
              //创建列表
              this.createlist.push(items);
            } else {
              //授权的话滑动是禁用的
              items.isnohua = true;
              //授权列表
              this.entrustlist.push(items);
            }
            for (let itt of items.points) {
              if (itt.picUrl.length !== 0 && itt.picUrl[0] !== "") {
                var arr = [];
                for (let val of itt.picUrl) {
                  arr.push(getApp().globalData.serverAddress + val);
                }
                itt.picUrl = arr;
              } else {
                itt.picUrl[0] = "/static/img/NoPictures.png";
              }
            }
          }
          this.count = this.createlist.length;
          this.equipmentList = this.createlist;
          if (this.count < this.pageSize) {
            this.loadStatus = "nomore";
            if (this.createlist.length !== 0) {
              this.noData = false;
            } else {
              this.noData = true;
              this.nodatatitle = "您还没有创建设备，请先创建需要监测的设备。";
            }
          } else {
            this.loadStatus = "loadmore";
          }
        } else {
          this.$utils.showToast(this, res.data.msg, "error");
        }
      },
      fail(res) {
        this.$utils.showToast(this, "加载失败！", "error");
      },
      complete() {
        uni.hideLoading();
        if (parameter.number == 0) {
          uni.showModal({
            confirmColor: "#2979ff",
            cancelText: "否",
            confirmText: "是",
            content: "设备创建成功！是否立即为该设备创建测点？",
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url:
                    "/pages/equipmentManage/addPoint?equipmentRealId=" +
                    parameter.EQid,
                });
              }
            },
          });
        } else if (parameter.number == 1) {
          uni.showModal({
            confirmColor: "#2979ff",
            cancelText: "否",
            confirmText: "是",
            content: "新增测点成功！是否立即为该测点绑定传感器？",
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url:
                    "/pages/sensor/addSensor?pointRealId=" +
                    parameter.POid +
                    "&equipmentRealId=" +
                    parameter.EQid,
                });
              }
            },
          });
        }
      },
    });
  },
  methods: {
    //点击横向列表
    clicktab(index) {
      this.current = index.id;
      if (index.id == 1) {
        this.nodatatitle = "您还没有创建设备，请先创建需要监测的设备。";
        for (let item of this.createlist) {
          item.isnohua = false;
        }
        this.equipmentList = this.createlist;
      } else {
        this.nodatatitle = "您还没有被授权设备，请联系其他用户进行设备授权。";
        this.equipmentList = this.entrustlist;
      }
    },
    //删除设备
    EQdelclick(value) {
      uni.showModal({
        content:
          "此操作会同时删除设备下所有测点已采集的数据记录及报警记录，并自动解绑所有已绑定的传感器，是否确定删除？",
        success: (res) => {
          if (res.confirm) {
            uni.request({
              url:
                getApp().globalData.serverAddress +
                this.$uri.Uri_delequipment.replace(
                  "{userRealId}",
                  this.userinfo.userRealId
                ).replace("{equipmentRealId}", value.equipmentRealId),
              method: "POST",
              success: (resData) => {
                if (resData.statusCode !== 200) {
                  this.$utils.showToast(
                    this,
                    "服务器错误,请联系技术支持人员!",
                    "error"
                  );
                  return;
                }
                this.getEquipmentList();
                this.$utils.showToast(this, "删除成功！", "success");
              },
              fail: (resData) => {
                this.$utils.showToast(this, resData.data.msg, "error");
              },
            });
          }
        },
      });
    },
    //返回
    onLeftClick() {
      uni.switchTab({
        url: "/pages/tabbar/userCenter",
      });
    },
    //跳转新增设备
    gotoAdd() {
      uni.navigateTo({
        url: "/pages/equipmentManage/addEquipment",
      });
    },
    //获取设备列表
    getEquipmentList() {
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });
      //获取设备列表之前清空授权列表
      let creatarr = this.createlist;
      this.createlist = [];
      this.entrustlist = [];
      uni.request({
        url:
          getApp().globalData.serverAddress +
          this.$uri.Uri_lookEquipmentList.replace(
            "{userRealId}",
            this.userinfo.userRealId
          ),
        data: {
          page: this.pageIndex,
          limit: this.pageSize,
          Name: this.searchKeyword,
          showCreated: this.showCreated,
          showAssigned: this.showAssigned,
        },
        dataType: "json",
        method: "GET",
        success: (res) => {
          if (res.statusCode !== 200) {
            this.$utils.showToast(
              this,
              "服务器错误,请联系技术支持人员!",
              "error"
            );
            return;
          }
          if (res.data.code == 0) {
            for (let items of res.data.data) {
              if (items.picUrl.length !== 0 && items.picUrl[0] !== "") {
                var arr = [];
                for (let val of items.picUrl) {
                  arr.push(getApp().globalData.serverAddress + val);
                }
                items.picUrl = arr;
              } else {
                items.picUrl[0] = "/static/img/NoPictures.png";
              }
              if (items.assignFlag == 0) {
                items.isnohua = false;
                //循环遍历以前的创建设备列表
                for (let itee of creatarr) {
                  //如果设备编号一样的话,将以前的设备的是否滑动赋值给现在的设备
                  if (items.equipmentRealId == itee.equipmentRealId) {
                    items.isnohua = itee.isnohua;
                  }
                }
                this.createlist.push(items);
              } else {
                //授权的话滑动是禁用的
                items.isnohua = true;
                this.entrustlist.push(items);
              }
              for (let itt of items.points) {
                if (itt.picUrl.length !== 0 && itt.picUrl[0] !== "") {
                  var arr = [];
                  for (let val of itt.picUrl) {
                    arr.push(getApp().globalData.serverAddress + val);
                  }
                  itt.picUrl = arr;
                } else {
                  itt.picUrl[0] = "/static/img/NoPictures.png";
                }
              }
            }
            //判断当前是创建还是授权
            if (this.current == 1) {
              //创建
              this.count = this.createlist.length;
              this.equipmentList = this.createlist;
            } else {
              this.count = this.entrustlist.length;
              this.equipmentList = this.entrustlist;
            }
            if (this.count < this.pageSize) {
              this.loadStatus = "nomore";
            } else {
              this.loadStatus = "loadmore";
            }
          } else {
            this.$utils.showToast(this, res.data.msg, "error");
          }
        },
        fail(res) {
          this.$utils.showToast(this, "加载失败！", "error");
        },
        complete() {
          uni.hideLoading();
        },
      });
    },
    //跳转到修改设备页面
    goEditEQ(value) {
      uni.navigateTo({
        url:
          "/pages/equipmentManage/editEquipment?equipmentRealId=" +
          value.equipmentRealId +
          "&entrust=" +
          value.assignFlag,
      });
    },
    //显示复制弹窗
    longpress(value) {
      if (value.assignFlag == 0) {
        this.copyvalue = value.name;
        this.copyequipmentid = value.equipmentRealId;
        this.show = true;
      }
    },
    //确定复制
    confirm() {
      if (this.copyvalue.length >= 2 && this.copyvalue.length <= 20) {
        uni.showLoading({
          title: "复制中...",
          mask: true,
        });
        uni.request({
          url:
            getApp().globalData.serverAddress +
            this.$uri.Uri_copyEquipment.replace(
              "{userRealId}",
              this.userinfo.userRealId
            ).replace("{equipmentRealId}", this.copyequipmentid),
          data: {
            Name: this.copyvalue,
          },
          dataType: "json",
          method: "POST",
          success: (res) => {
            if (res.statusCode !== 200) {
              this.$utils.showToast(
                this,
                "服务器错误,请联系技术支持人员!",
                "error"
              );
              return;
            }
            if (res.data.code == 0) {
              this.show = false;
              this.$utils.showToast(this, "复制成功！", "success");
              this.getEquipmentList();
            } else {
              uni.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 2000,
                mask: true,
              });
            }
          },
          fail(res) {
            uni.showToast({
              title: "复制失败！",
              icon: "none",
              duration: 2000,
              mask: true,
            });
          },
          complete() {
            uni.hideLoading();
          },
        });
      } else {
        uni.showToast({
          title: "设备名称长度在2-20个字符之间",
          icon: "none",
          duration: 2000,
          mask: true,
        });
      }
    },
    //打开折叠面板
    collapse(value) {
      if (value.assignFlag == 0) {
        if (value.isnohua) {
          value.isnohua = false;
        } else {
          value.isnohua = true;
        }
      } else {
        value.isnohua = true;
      }
    },
    //新增测点
    addpoint(value) {
      uni.navigateTo({
        url:
          "/pages/equipmentManage/addPoint?equipmentRealId=" +
          value.equipmentRealId,
      });
    },
    //删除测点
    delPOclick(eq, po) {
      uni.showModal({
        content:
          "此操作会同时删除该测点下所有已采集的数据记录及报警记录，并自动解绑当前所绑定的传感器，是否确定删除？",
        success: (res) => {
          if (res.confirm) {
            uni.request({
              url:
                getApp().globalData.serverAddress +
                this.$uri.Uri_delpoint.replace(
                  "{userRealId}",
                  this.userinfo.userRealId
                )
                  .replace("{equipmentRealId}", eq.equipmentRealId)
                  .replace("{pointRealId}", po.pointRealId),
              method: "POST",
              success: (resData) => {
                if (resData.statusCode !== 200) {
                  this.$utils.showToast(
                    this,
                    "服务器错误,请联系技术支持人员!",
                    "error"
                  );
                  return;
                }
                this.getEquipmentList();
                this.$utils.showToast(this, "删除成功！", "success");
              },
              fail: (resData) => {
                this.$utils.showToast(this, resData.data.msg, "error");
              },
            });
          }
        },
      });
    },
    //修改测点
    goEditPO(eq, po) {
      let parameterinfo = {
        pointRealId: po.pointRealId,
        equipmentRealId: eq.equipmentRealId,
        entrust: eq.assignFlag,
      };
      let parameterinfodata = JSON.stringify(parameterinfo);
      uni.navigateTo({
        url: `/pages/equipmentManage/editPoint?content=${encodeURIComponent(
          parameterinfodata
        )}`,
      });
    },
    //传感器详情
    gosensor(eq, po) {
      if (
        po.deviceMac !== null &&
        po.deviceMac !== "" &&
        po.deviceMac !== undefined
      ) {
        uni.navigateTo({
          url: "/pages/sensor/sensor?macCode=" + po.deviceMac,
        });
      } else {
        uni.navigateTo({
          url:
            "/pages/sensor/addSensor?pointRealId=" +
            po.pointRealId +
            "&equipmentRealId=" +
            eq.equipmentRealId,
        });
      }
    },
    //报警值配置
    setabnormal(eq, po) {
      var nametitle = eq.name + "-" + po.name;
      uni.navigateTo({
        url:
          "/pages/equipmentManage/featureList?pointRealId=" +
          po.pointRealId +
          "&equipmentRealId=" +
          eq.equipmentRealId +
          "&name=" +
          nametitle +
          "&entrust=" +
          eq.assignFlag,
      });
    },
    //下滑加载
    scrolltolower() {
      if (this.count < this.pageSize) {
        this.loadStatus = "nomore";
      } else {
        setTimeout(() => {
          this.loadStatus = "loading";
          this.pageSize += 8;
          this.getEquipmentList();
        }, 1000);
      }
    },
  },
  //下拉刷新
  onPullDownRefresh() {
    this.pageSize = 8;
    this.getEquipmentList();
    uni.stopPullDownRefresh();
  },
};
</script>

<style lang="scss">
@import "@/common/uni-ui.scss";

.uni-list--border-top {
  z-index: 99 !important;
}

.swipecolleq {
  width: 90%;
  margin: 2% auto;
  border-radius: 15px;
  overflow: hidden;
}

.slot-box {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
}

.slot-text {
  flex: 1;
  font-size: 14px;
}

.slotheader {
  width: 25%;
  height: 140rpx;
  border-radius: 5px;
  overflow: hidden;
}

.u-album__row__wrapper {
  width: 140rpx;
  height: 140rpx;
}

.slotbody {
  padding: 10px;
  width: 60%;
  word-wrap: break-word;
}

.slotbo {
  padding: 10px;
  width: 80%;
  word-wrap: break-word;
}

.slottitle {
  font-size: 15px;
  color: #303133;
}

.slottext {
  margin-top: 6rpx;
  font-size: 13px;
  color: #8f939c;
}

.uni-description {
  font-size: 13px;
  color: #2797ff;
}

.slotfooter {
  width: 40%;
  padding: 5% 0%;
}

.slotfooter view {
  display: inline-block;
  width: 80rpx;
  color: #fff;
  border-radius: 40rpx;
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  margin-left: 10rpx;
}

.xinzeng {
  width: 100%;
  text-align: center;
}
.header {
  width: 320px;
  height: 240px;
  margin: 80px auto 0px;
}

.title {
  width: 100%;
  font-size: 15px;
  color: #a8a8a8;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20rpx 0rpx;
  padding: 0px 45px;
}
</style>